<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>pgmpy.estimators.MLE &#8212; pgmpy 0.1.2 documentation</title>
    
    <link rel="stylesheet" href="../../../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../../',
        VERSION:     '0.1.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" /> 
  </head>
  <body role="document">
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../index.html" accesskey="U">Module code</a> &#187;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../../../index.html">
              <img class="logo" src="../../../_static/logo.png" alt="Logo"/>
            </a></p>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../../../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <h1>Source code for pgmpy.estimators.MLE</h1><div class="highlight"><pre>
<span></span><span class="c1"># coding:utf-8</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>

<span class="kn">from</span> <span class="nn">pgmpy.estimators</span> <span class="k">import</span> <span class="n">ParameterEstimator</span>
<span class="kn">from</span> <span class="nn">pgmpy.factors.discrete</span> <span class="k">import</span> <span class="n">TabularCPD</span>
<span class="kn">from</span> <span class="nn">pgmpy.models</span> <span class="k">import</span> <span class="n">BayesianModel</span>


<div class="viewcode-block" id="MaximumLikelihoodEstimator"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.MLE.MaximumLikelihoodEstimator">[docs]</a><span class="k">class</span> <span class="nc">MaximumLikelihoodEstimator</span><span class="p">(</span><span class="n">ParameterEstimator</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Class used to compute parameters for a model using Maximum Likelihood Estimation.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        model: A pgmpy.models.BayesianModel instance</span>

<span class="sd">        data: pandas DataFrame object</span>
<span class="sd">            DataFrame object with column names identical to the variable names of the network.</span>
<span class="sd">            (If some values in the data are missing the data cells should be set to `numpy.NaN`.</span>
<span class="sd">            Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)</span>

<span class="sd">        state_names: dict (optional)</span>
<span class="sd">            A dict indicating, for each variable, the discrete set of states</span>
<span class="sd">            that the variable can take. If unspecified, the observed values</span>
<span class="sd">            in the data set are taken to be the only possible states.</span>

<span class="sd">        complete_samples_only: bool (optional, default `True`)</span>
<span class="sd">            Specifies how to deal with missing data, if present. If set to `True` all rows</span>
<span class="sd">            that contain `np.NaN` somewhere are ignored. If `False` then, for each variable,</span>
<span class="sd">            every row where neither the variable nor its parents are `np.NaN` is used.</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; import numpy as np</span>
<span class="sd">        &gt;&gt;&gt; import pandas as pd</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.models import BayesianModel</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.estimators import MaximumLikelihoodEstimator</span>
<span class="sd">        &gt;&gt;&gt; data = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)),</span>
<span class="sd">        ...                       columns=[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;])</span>
<span class="sd">        &gt;&gt;&gt; model = BayesianModel([(&#39;A&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;D&#39;), (&#39;B&#39;, &#39;E&#39;)])</span>
<span class="sd">        &gt;&gt;&gt; estimator = MaximumLikelihoodEstimator(model, data)</span>
<span class="sd">        &quot;&quot;&quot;</span>

        <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">BayesianModel</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s2">&quot;Maximum Likelihood Estimate is only implemented for BayesianModel&quot;</span><span class="p">)</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">MaximumLikelihoodEstimator</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

<div class="viewcode-block" id="MaximumLikelihoodEstimator.get_parameters"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.MLE.MaximumLikelihoodEstimator.get_parameters">[docs]</a>    <span class="k">def</span> <span class="nf">get_parameters</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Method to estimate the model parameters (CPDs) using Maximum Likelihood Estimation.</span>

<span class="sd">        Returns</span>
<span class="sd">        -------</span>
<span class="sd">        parameters: list</span>
<span class="sd">            List of TabularCPDs, one for each variable of the model</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; import numpy as np</span>
<span class="sd">        &gt;&gt;&gt; import pandas as pd</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.models import BayesianModel</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.estimators import MaximumLikelihoodEstimator</span>
<span class="sd">        &gt;&gt;&gt; values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)),</span>
<span class="sd">        ...                       columns=[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;])</span>
<span class="sd">        &gt;&gt;&gt; model = BayesianModel([(&#39;A&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;D&#39;))</span>
<span class="sd">        &gt;&gt;&gt; estimator = MaximumLikelihoodEstimator(model, values)</span>
<span class="sd">        &gt;&gt;&gt; estimator.get_parameters()</span>
<span class="sd">        [&lt;TabularCPD representing P(C:2) at 0x7f7b534251d0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(B:2 | C:2, A:2) at 0x7f7b4dfd4da0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(A:2) at 0x7f7b4dfd4fd0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(D:2 | C:2) at 0x7f7b4df822b0&gt;]</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">parameters</span> <span class="o">=</span> <span class="p">[]</span>

        <span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">nodes</span><span class="p">()):</span>
            <span class="n">cpd</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">estimate_cpd</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>
            <span class="n">parameters</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">cpd</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">parameters</span></div>

<div class="viewcode-block" id="MaximumLikelihoodEstimator.estimate_cpd"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.MLE.MaximumLikelihoodEstimator.estimate_cpd">[docs]</a>    <span class="k">def</span> <span class="nf">estimate_cpd</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Method to estimate the CPD for a given variable.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        node: int, string (any hashable python object)</span>
<span class="sd">            The name of the variable for which the CPD is to be estimated.</span>

<span class="sd">        Returns</span>
<span class="sd">        -------</span>
<span class="sd">        CPD: TabularCPD</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; import pandas as pd</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.models import BayesianModel</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.estimators import MaximumLikelihoodEstimator</span>
<span class="sd">        &gt;&gt;&gt; data = pd.DataFrame(data={&#39;A&#39;: [0, 0, 1], &#39;B&#39;: [0, 1, 0], &#39;C&#39;: [1, 1, 0]})</span>
<span class="sd">        &gt;&gt;&gt; model = BayesianModel([(&#39;A&#39;, &#39;C&#39;), (&#39;B&#39;, &#39;C&#39;)])</span>
<span class="sd">        &gt;&gt;&gt; cpd_A = MaximumLikelihoodEstimator(model, data).estimate_cpd(&#39;A&#39;)</span>
<span class="sd">        &gt;&gt;&gt; print(cpd_A)</span>
<span class="sd">        ╒══════╤══════════╕</span>
<span class="sd">        │ A(0) │ 0.666667 │</span>
<span class="sd">        ├──────┼──────────┤</span>
<span class="sd">        │ A(1) │ 0.333333 │</span>
<span class="sd">        ╘══════╧══════════╛</span>
<span class="sd">        &gt;&gt;&gt; cpd_C = MaximumLikelihoodEstimator(model, data).estimate_cpd(&#39;C&#39;)</span>
<span class="sd">        &gt;&gt;&gt; print(cpd_C)</span>
<span class="sd">        ╒══════╤══════╤══════╤══════╤══════╕</span>
<span class="sd">        │ A    │ A(0) │ A(0) │ A(1) │ A(1) │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼──────┤</span>
<span class="sd">        │ B    │ B(0) │ B(1) │ B(0) │ B(1) │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼──────┤</span>
<span class="sd">        │ C(0) │ 0.0  │ 0.0  │ 1.0  │ 0.5  │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼──────┤</span>
<span class="sd">        │ C(1) │ 1.0  │ 1.0  │ 0.0  │ 0.5  │</span>
<span class="sd">        ╘══════╧══════╧══════╧══════╧══════╛</span>
<span class="sd">        &quot;&quot;&quot;</span>

        <span class="n">state_counts</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">state_counts</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>

        <span class="c1"># if a column contains only `0`s (no states observed for some configuration</span>
        <span class="c1"># of parents&#39; states) fill that column uniformly instead</span>
        <span class="n">state_counts</span><span class="o">.</span><span class="n">ix</span><span class="p">[:,</span> <span class="p">(</span><span class="n">state_counts</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()]</span> <span class="o">=</span> <span class="mi">1</span>

        <span class="n">parents</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">get_parents</span><span class="p">(</span><span class="n">node</span><span class="p">))</span>
        <span class="n">parents_cardinalities</span> <span class="o">=</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="n">parent</span><span class="p">])</span> <span class="k">for</span> <span class="n">parent</span> <span class="ow">in</span> <span class="n">parents</span><span class="p">]</span>
        <span class="n">node_cardinality</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="n">node</span><span class="p">])</span>

        <span class="n">cpd</span> <span class="o">=</span> <span class="n">TabularCPD</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="n">node_cardinality</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">state_counts</span><span class="p">),</span>
                         <span class="n">evidence</span><span class="o">=</span><span class="n">parents</span><span class="p">,</span>
                         <span class="n">evidence_card</span><span class="o">=</span><span class="n">parents_cardinalities</span><span class="p">,</span>
                         <span class="n">state_names</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">)</span>
        <span class="n">cpd</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cpd</span></div></div>
</pre></div>

          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../index.html" >Module code</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2016, Ankur Ankan.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.1.
    </div>
  </body>
</html>